var express = require('express');
var router = express.Router();
var	mongoose = require('mongoose'),
	memberUsers = mongoose.model('member_users');

/* 获取验证码. */
router.post('/getVerificationCode', function(req, res, next) {
	let params = req.body;

	const SMSClient = require('@alicloud/sms-sdk')
 
	// ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换 
	const accessKeyId = 'LTAIeigahZkeWnMy'
	const secretAccessKey = 'wifHbYbZGJ4ml85KSWRCAg9RkhcoqU'
	 
	//在云通信页面开通相应业务消息后，就能在页面上获得对应的queueName,不用填最后面一段 
	const queueName = 'Alicom-Queue-1092397003988387-'
	 
	//初始化sms_client 
	let smsClient = new SMSClient({accessKeyId, secretAccessKey})
	
	let code6 = (Math.random() + '').slice(2, 8);
	//发送短信
	smsClient.sendSMS({
	    PhoneNumbers: params.mobile,
	    SignName: '美艺天',
	    TemplateCode: 'SMS_112475790',
	    TemplateParam: '{"code":"'+ code6 +'","product":"云通信"}'
	}).then(function (data) {
	    let {Code} = data;
	    if (Code === 'OK') {
	        //处理返回参数
	        res.json({
	        	code: code6
	        })
	    }
	}, function (err) {
	    console.log(err)
	})
});

/* 登录. */
router.post('/goLogin', function(req, res, next) {
	let params = req.body;

	memberUsers.find({
		mobile: params.mobile,
		passWord: params.password
	}, function(err, data){
		if(err){
			res.json({
				result: 0,
				error: '数据获取失败'
			});
		}else{
			if(data.length){
				res.json(data[0]);
			}else{
				res.json({
					error: '查无此人，请检查帐号密码！'
				});
			}
		}
	})
});

/* 验证帐号是否存在. */
router.post('/verificationMobile', function(req, res, next) {
	let params = req.body;

	memberUsers.find({
		mobile: params.mobile,
	}, function(err, data){
		err && res.json(err);

		if(data.length){
			res.json({
				error: '手机已被注册！'
			});
		}else{
			res.end();
		}
	})
});

/* 注册. */
router.post('/register', function(req, res, next) {
	let params = req.body;

	let saveData = new memberUsers(params);
	saveData.save(err => {
		if(err){
			res.json({
				error: '注册失败，请联系管理员！'
			})
		}else{
			res.json({
				mobile: params.mobile,
				userName: '---'
			})
		}
	})
});

module.exports = router;
